home *** CD-ROM | disk | FTP | other *** search
- Path: rcp6.elan.af.mil!rscernix!danpop
- From: danpop@mail.cern.ch (Dan Pop)
- Newsgroups: comp.lang.c
- Subject: Re: Help With Pointers
- Date: 23 Feb 96 12:18:18 GMT
- Organization: CERN European Lab for Particle Physics
- Message-ID: <danpop.825077898@rscernix>
- References: <4g67cj$6cv@hobbes.compusult.nf.ca> <4ggvnq$2bt@newshost.cyberramp.net>
- NNTP-Posting-Host: ues5.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
-
- In <4ggvnq$2bt@newshost.cyberramp.net> sinan@cyberramp.net (John Noland) writes:
-
- >In article <4g67cj$6cv@hobbes.compusult.nf.ca>, bryan@public.compusult.nf.ca says...
- >>
- >>Is there any way to assign a char pointer to a float pointer?
- >>
- >>I had to do some byte rotation on binary data. I rotated
- >>the characters and know want to point a float at the first
- >>character position to read back a 4 byte float.
-
- float *p = (float *)buff;
-
- This will work on the PC, but it's not a great idea, because buff may not
- be correctly aligned for a float. On the PC this will only cause a
- performance penalty, on other platforms the program will crash and burn
- with a bus error.
-
- The correct way is to do it the other way round:
-
- float f;
- unsigned char *p = (unsigned char *) &f;
-
- Now you can use p to copy the bytes in, fixing the ordering during the
- copy operation (or after) and when you're done, f will contain the right
- value.
-
- >>I'am actually trying to read SGI binary data with a PC. I've been told
- >>that the SGI bytes ( not bits ) are rotated versus a PC. Any help
- >>would be appreciated. Are the bytes rotated?
-
- No, you have to rotate them yourself :-)
-
- >variable. So, you might wind up with something like this;
- >
- >char SGI_source[4];
- >union {
- > char d1[4];
- > float d2;
- >} dest;
- >
- >dest.d1[1] = SGI_source[2];
- >dest.d2[2] = SGI_source[1];
- ^^
- ??
- >
- >or however the byte rotation needs to be done.
-
- Using a union for this purpose is a bit of overkill (and, as you just
- proved, error prone :-), a pointer is all that is needed:
-
- float f;
- unsigned char *p = (unsigned char *) &f, buff[sizeof(float)];
- int i;
-
- p += sizeof(float);
- for(i = 0; i < sizeof(float); i++)
- *(--p) = buff[i]; /* the parentheses are actually superfluous :-) */
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-